package org.crystalcore;

import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BlockStateMeta;

import java.util.List;

public class ItemFrame implements Listener {

    @EventHandler
    public void onPlayerInteract(PlayerInteractEvent event) {
        Player player = event.getPlayer();
        if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
            Block clickedBlock = event.getClickedBlock();
            if (clickedBlock != null && clickedBlock.getType() == Material.ITEM_FRAME) {
                ItemFrame itemFrame = getItemFrame(clickedBlock);
                if (itemFrame != null && itemFrame.getItem().getType() != Material.AIR) {
                    ItemStack displayedItem = itemFrame.getItem();
                    player.getInventory().addItem(displayedItem);
                    itemFrame.setItem(new ItemStack(Material.AIR));
                }
            }
        }
    }

    @EventHandler
    public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
        Player player = event.getPlayer();
        if (event.getRightClicked() instanceof ItemFrame) {
            ItemFrame itemFrame = (ItemFrame) event.getRightClicked();
            if (itemFrame.getItem().getType() != Material.AIR) {
                ItemStack displayedItem = itemFrame.getItem();
                player.getInventory().addItem(displayedItem);
                itemFrame.setItem(new ItemStack(Material.AIR));
            }
        }
    }

    private ItemFrame getItemFrame(Block block) {
        for (BlockFace face : BlockFace.values()) {
            if (block.getRelative(face).getState() instanceof ItemFrame) {
                return (ItemFrame) block.getRelative(face).getState();
            }
        }
        return null;
    }
}

